package com.hongri.recyclerview.thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import com.hongri.recyclerview.utils.Logger;

/**
 * Created by zhongyao on 2017/4/26.
 * 具有暂停功能的优先级线程池
 */

public class PausableThreadPoolExecutor extends ThreadPoolExecutor {

    private String TAG = PausableThreadPoolExecutor.class.getSimpleName();
    public static boolean isPaused;
    private ReentrantLock pauseLock = new ReentrantLock();
    private Condition unpaused = pauseLock.newCondition();

    public PausableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        pauseLock.lock();
        try {
            while (isPaused) {
                unpaused.await();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            pauseLock.unlock();
        }
        Logger.d(TAG + "---线程：" + t.getName() + "--准备执行任务");
    }

    public void pause() {
        pauseLock.lock();
        try {
            isPaused = true;
        } finally {
            pauseLock.unlock();
        }
    }

    public void resume() {
        pauseLock.lock();
        try {
            isPaused = false;
            unpaused.signalAll();
        } finally {
            pauseLock.unlock();
        }
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        Logger.d(TAG + "---线程：" + Thread.currentThread().getName() + "--执行任务结束");
    }

    @Override
    protected void terminated() {
        super.terminated();
        Logger.d("线程池结束!");
    }
}
